Component({
  properties: {
    // 图片列表
    files: {
      type: Array,
      value: []
    },
    // 最大上传数量
    maxCount: {
      type: Number,
      value: 9
    },
    // 业务类型
    bizType: {
      type: String,
      value: 'review_images' // 默认为评论图片
    },
    // 图片最大尺寸，单位KB
    maxSize: {
      type: Number,
      value: 5 * 1024 // 默认5MB
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      value: false
    },
    // 列数
    column: {
      type: Number,
      value: 3
    },
    // 是否显示添加按钮
    showAdd: {
      type: Boolean,
      value: true
    },
    // 是否显示删除按钮
    showDelete: {
      type: Boolean,
      value: true
    },
    // 图片宽度
    width: {
      type: String,
      value: '216rpx'
    },
    // 图片高度
    height: {
      type: String,
      value: '216rpx'
    }
  },
  data: {
    // 上传状态
    uploading: false,
    // 业务类型枚举
    bizTypes: {
      SERVICES_IMAGES: 'services_images',
      REVIEW_IMAGES: 'review_images',
      CATEGORY_IMAGE: 'category_image',
      AFTER_SALES_IMAGES: 'after_sales_images',
      USER_AVATAR: 'user_avatar'
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      if (this.data.uploading || this.properties.disabled) {
        return;
      }

      const { maxCount, files } = this.properties;
      const remainCount = maxCount - files.length;

      if (remainCount <= 0) {
        wx.showToast({
          title: `最多上传${maxCount}张图片`,
          icon: 'none'
        });
        return;
      }

      wx.chooseMedia({
        count: remainCount,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        camera: 'back',
        success: (res) => {
          this.uploadFiles(res.tempFiles);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },

    // 上传文件
    uploadFiles(tempFiles) {
      if (!tempFiles || tempFiles.length === 0) {
        return;
      }

      // 设置上传中状态
      this.setData({ uploading: true });

      // 统计上传成功和失败数量
      let successCount = 0;
      let failCount = 0;
      const totalCount = tempFiles.length;
      const uploadResults = [];

      // 检查文件大小
      const { maxSize } = this.properties;
      const validFiles = tempFiles.filter(file => {
        const isValid = file.size <= maxSize * 1024; // 转换为字节
        if (!isValid) {
          failCount++;
          wx.showToast({
            title: `图片不能超过${maxSize / 1024}MB`,
            icon: 'none'
          });
        }
        return isValid;
      });

      if (validFiles.length === 0) {
        this.setData({ uploading: false });
        return;
      }

      // 获取token
      const token = wx.getStorageSync('token');
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        this.setData({ uploading: false });
        return;
      }

      // 并行上传所有图片
      const uploadTasks = validFiles.map((file, index) => {
        return new Promise((resolve, reject) => {
          const uploadTask = wx.uploadFile({
            url: `${getApp().globalData.baseUrl}/api/file/upload`,
            filePath: file.tempFilePath,
            name: 'file',
            header: {
              'Authorization': token
            },
            formData: {
              'biz': this.properties.bizType
            },
            success: (res) => {
              // 解析返回结果
              try {
                const result = JSON.parse(res.data);
                if (result.code === 0 && result.data) {
                  successCount++;
                  resolve({
                    url: result.data,
                    uploadTime: new Date().getTime(),
                    index: index
                  });
                } else {
                  failCount++;
                  reject(new Error(result.message || '上传失败'));
                }
              } catch (err) {
                failCount++;
                reject(err);
              }
            },
            fail: (err) => {
              failCount++;
              reject(err);
            }
          });

          // 监听上传进度
          uploadTask.onProgressUpdate((res) => {
          });
        });
      });

      // 处理所有上传任务
      Promise.all(uploadTasks.map(p => p.catch(e => e)))
        .then(results => {
          // 过滤出成功的结果
          const successResults = results.filter(res => !(res instanceof Error));

          // 更新图片列表
          const newFiles = [...this.properties.files, ...successResults];

          // 触发更新事件
          this.triggerEvent('change', { files: newFiles });

          // 显示结果
          if (successCount > 0) {
            wx.showToast({
              title: failCount > 0
                ? `成功上传${successCount}张，失败${failCount}张`
                : `成功上传${successCount}张图片`,
              icon: 'none'
            });
          } else if (failCount > 0) {
            wx.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('上传图片错误:', err);
          wx.showToast({
            title: '上传出错，请重试',
            icon: 'none'
          });
        })
        .finally(() => {
          this.setData({ uploading: false });
        });
    },

    // 预览图片
    previewImage(e) {
      const { index } = e.currentTarget.dataset;
      const { files } = this.properties;

      if (files && files.length > 0) {
        wx.previewImage({
          urls: files.map(file => file.url),
          current: files[index].url
        });
      }
    },

    // 删除图片
    deleteImage(e) {
      const { index } = e.currentTarget.dataset;
      const { files } = this.properties;

      if (this.properties.disabled) {
        return;
      }

      wx.showModal({
        title: '提示',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            const newFiles = [...files];
            newFiles.splice(index, 1);

            // 触发更新事件
            this.triggerEvent('change', { files: newFiles });
          }
        }
      });
    }
  }
}) 